package com.rabbit.eap.framework.utils;

import com.rabbit.eap.config.constant.CommonRedisKey;
import com.rabbit.eap.framework.shiro.util.JwtTokenUtil;
import com.rabbit.eap.framework.shiro.util.JwtUtil;
import com.rabbit.eap.framework.shiro.vo.LoginSysUserRedisVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @projectName eap
 * @packageName com.rabbit.eap.framework.utils
 * @className LoginUtil
 * @author： rabbit
 * @version： 1.0
 * @since： 2020/4/21 21:55
 * <p>Description: LoginUtil
 * 获取登录信息工具类
 * </p>

 */
@Slf4j
@Component
public class LoginUtil {

    private static RedisTemplate redisTemplate;

    public LoginUtil(RedisTemplate redisTemplate) {
        LoginUtil.redisTemplate = redisTemplate;
    }


    /**
     * 获取当前登录用户对象
     *
     * @return
     */
    public static LoginSysUserRedisVO getLoginSysUserRedisVo() {
        // 获取当前登录用户
        String token = JwtTokenUtil.getToken();
        if(StringUtils.isBlank(token)){
            return null;
        }
        String username = JwtUtil.getUsername(token);
        if (StringUtils.isBlank(username)) {
            return null;
        }
        return (LoginSysUserRedisVO) redisTemplate.opsForValue().get(String.format(CommonRedisKey.LOGIN_USER, username));
    }

    /**
     * 获取当前登录用户的ID
     *
     * @return
     */
    public static Long getUserId() {
        LoginSysUserRedisVO loginSysUserRedisVo = getLoginSysUserRedisVo();
        if (loginSysUserRedisVo == null) {
            return null;
        }
        return loginSysUserRedisVo.getId();
    }

    /**
     * 获取当前登录用户的账号
     *
     * @return
     */
    public static String getUsername() {
        LoginSysUserRedisVO loginSysUserRedisVo = getLoginSysUserRedisVo();
        if (loginSysUserRedisVo == null) {
            return null;
        }
        return loginSysUserRedisVo.getUserName();
    }

}

